package org.vates.practicofinal.web.backingbean;

import java.io.IOException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.vates.practicofinal.dao.model.User;
import org.vates.practicofinal.service.UserService;

@ManagedBean
@SessionScoped
@Component
public class UserBean {
	
	@Autowired
	private UserService userService;
	
	private User user = new User();

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	public String doSave() throws IOException {
		user.setEnabled(true);
		userService.save(user);			

		FacesContext.getCurrentInstance().getExternalContext().redirect("userList.xhtml");
		return "";
	}
	
	public String editUser(Long userId) throws IOException {
		user = userService.get(new Long(userId));
		FacesContext.getCurrentInstance().getExternalContext().redirect("userEdit.xhtml");
		return "";
	}
	
	public String newUser() throws IOException {
		user = new User();		

		FacesContext.getCurrentInstance().getExternalContext().redirect("userEdit.xhtml");
		return "";
	}	

	public String deleteUser(Long userId) throws IOException {
		user = userService.get(new Long(userId));
		userService.delete(user);
		return "";
	}
	
	public String disableUser(Long userId) throws IOException {
		user = userService.get(new Long(userId));
		user.setEnabled(false);
		userService.save(user);	
		return "";
	}
}
